#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 匿名函数捕获变量值
问题: 你用lambda定义了一个匿名函数，并想在定义时捕获到某些变量的值
提示 : 
    1. 通过使用函数默认值参数形式，lambda函数在定义时就能绑定到值。
"""

def recipe1():
    x = 10
    a = lambda y: x + y
    x = 20
    b = lambda y: x + y
    print(f"{a(10) = }")
    print(f"{b(10) = }")

    x = 15
    print(f"{a(10) = }")


def recipe2():
    '''让某个匿名函数在定义时就捕获到值，可以将那个参数值定义成默认参数即可'''
    x = 10
    a = lambda y, x=x: x + y
    x = 20
    b = lambda y, x=x: x + y
    print(f"{a(10) = }")
    print(f"{b(10) = }")

def recipe3():
    funcs = [lambda x: x+n for n in range(5)]       #NOSONAR
    for f in funcs:
        print(f"{f(0) = }")

def recipe4():
    funcs = [lambda x, n=n: x+n for n in range(5)]
    for f in funcs:
        print(f"{f(0) = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main()       